<?php
require_once( 'Classes/Datasources/DatasourceDecorator.php' );

class CachedDatasource extends DatasourceDecorator {

	var $iLastDdl;
	var $sDatasourceId;
	
	function CachedDatasource( $oDatasource ) {
		
		$this->DatasourceDecorator( $oDatasource );
		$this->sDatasourceId = $this->oDatasource->GetDatasourceId();
		$this->iLastDdl      =& Session::GetObject( $this->GetCacheName(), 'LastDdl' );

		$this->_CheckCacheIsUpToDate();

	}

	function GetCacheName() {
		return 'DatasourceCache.' . $this->sDatasourceId;
	}

	function ClearCache() {
		Session::InitialiseSection( $this->GetCacheName() );
	}

	function _CheckCacheIsUpToDate() {
		// The cache could timestamp everything that goes into it so we can check everything individually,
		// but since it's likely that most datasources won't change AT ALL during the time it's probably
		// most prudent to just check the once for everything

		$iDatasourceLastDdl = $this->oDatasource->GetLastDdl();
		if ( $this->iLastDdl && $this->iLastDdl < $iDatasourceLastDdl ) {
			Session::InitialiseSection( $this->GetCacheName() );
		}
		$this->iLastDdl = $iDatasourceLastDdl;
	}


	function GetCachedTableBasedItem( $sFunctionCall, $sTableName = null ) {
		$sCacheId = $sFunctionCall . '.' . $sTableName;
		$aReturn = Session::GetObject( $this->GetCacheName(), $sCacheId );
		if ( !$aReturn ) {
			$aReturn = $this->oDatasource->$sFunctionCall( $sTableName );
			Session::SaveObject( $this->GetCacheName(), $sCacheId, $aReturn );
		}
		return $aReturn;
	}
	
	function GetTableList() {
		return $this->GetCachedTableBasedItem( 'GetTableList' );
	}

	function GetColumnList( $sTableName ) {
		return $this->GetCachedTableBasedItem( 'GetColumnList', $sTableName );
	}
	
	function GetForeignKeys( $sTableName ) {
		return $this->GetCachedTableBasedItem( 'GetForeignKeys', $sTableName );
	}
	
	function GetPrimaryKey( $sTableName ) {
		return $this->GetCachedTableBasedItem( 'GetPrimaryKey', $sTableName );
	}
	
}

require_once( 'Classes/Session.php' );
?>
